/**
 * 是否有权限
 * @param routeName 当前页面路由名称
 * @param perms 权限按钮类型的值
 */
export function isAuth(routeName, perms) {
  let permListJson = JSON.parse(sessionStorage.getItem('AllPermissionList') || '[]');
  let permsTypeList = getPermsTypeListByRouteName(routeName, permListJson) || [];
  return permsTypeList.map(i => i.permsButtonType).indexOf(perms) !== -1 || false
}

/**
 * 根据路由名称从缓存中获取该路由页面拥有的按钮权限列表
 * @param routeName 当前页面路由名称
 * @param list 当前路由页面的子级
 */
export function getPermsTypeListByRouteName(routeName, list = JSON.parse(sessionStorage.getItem('AllPermissionList') || '[]')) {
  for (var i in list) {
    let jsonItem = list[i];
    let jsonArray = jsonItem.permissionChildList;
    if (jsonItem.url != routeName && jsonArray && jsonArray.length > 0) {
      let resultRoutelist = getPermsTypeListByRouteName(routeName, jsonArray);
      if (resultRoutelist && resultRoutelist.length > 0) {
        return resultRoutelist || [];
      }
    } else if (jsonItem.url == routeName) {
      return jsonItem.permissionChildList || [];
    }
  }
  return [];
}

// 将权限菜单转换为菜单列表
export function formatPermissionList(permsList) {
  let m = JSON.parse(JSON.stringify(permsList));

  function filterMenu(list) {
    return (list || []).filter(item => {
      return item.type === 1 && item.hideFlag === 1;
    });
  }

  function loopFunc(list) {
    list = filterMenu(list);
    (list || []).forEach(i => {
      if (i.permissionChildList && i.permissionChildList.length > 0) {
        i.permissionChildList = loopFunc(i.permissionChildList);
      }
    });
    return list;
  }
  return loopFunc(m);
}